package com.share.dgs.handler;

import com.netflix.graphql.dgs.exceptions.DefaultDataFetcherExceptionHandler;
import com.netflix.graphql.types.errors.TypedGraphQLError;
import com.share.dgs.exception.MyException;
import graphql.GraphQLError;
import graphql.execution.DataFetcherExceptionHandler;
import graphql.execution.DataFetcherExceptionHandlerParameters;
import graphql.execution.DataFetcherExceptionHandlerResult;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author caifan
 * @created 2021/7/17
 * @description:
 */
@Component
public class CustomDataFetchingExceptionHandler implements DataFetcherExceptionHandler  {

    private final DefaultDataFetcherExceptionHandler defaultHandler = new DefaultDataFetcherExceptionHandler();

    @Override
    public DataFetcherExceptionHandlerResult onException(DataFetcherExceptionHandlerParameters handlerParameters) {
        Throwable exception = handlerParameters.getException();
        if (exception instanceof MyException) {
            MyException myException = (MyException) exception;
            Map<String, Object> map = new HashMap<>();
            map.put("errorCode", myException.getErrorCode());
            map.put("errorMsg", myException.getErrorMsg());
            GraphQLError graphQLError = TypedGraphQLError.newBuilder()
                    .message(myException.getErrorCode(), myException.getErrorMsg())
                    .path(handlerParameters.getPath())
                    .extensions(map)
                    .build();

            return DataFetcherExceptionHandlerResult.newResult()
                    .error(graphQLError)
                    .build();
        } else {
            return defaultHandler.onException(handlerParameters);
        }
    }
}
